package app1.rapidsquare.com.fragment;


import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONObject;

import java.text.Collator;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;

import app1.rapidsquare.com.Utility.Utility;
import app1.rapidsquare.com.activity.MainActivity;
import app1.rapidsquare.com.activity.ProfileActivity;
import app1.rapidsquare.com.activity.R;
import app1.rapidsquare.com.adapter.ContactAdapter;
import app1.rapidsquare.com.classes.User;
import app1.rapidsquare.com.database.AgileContactsProvider;

public class ContactFragment extends AgileFragment {

    private EditText mEditTextSearch;
    private ListView mListViewContacts;
    private ContactAdapter mContactAdapter;
    private String mContactNote;
    private TextView mTextViewDontHaveConnection;
    private ImageView mImageViewSearch;

    public static ContactFragment newInstance() {
        return new ContactFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             final Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.fragment_contact, container, false);
        mEditTextSearch = (EditText) v.findViewById(R.id.editTextSearch);
        mImageViewSearch = (ImageView) v.findViewById(R.id.imageViewSearch);

        mListViewContacts = (ListView) v.findViewById(R.id.listViewContact);

        mListViewContacts.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Intent intent = new Intent(getActivity(),
                        ProfileActivity.class);
                User userContact = (User) mContactAdapter
                        .getItem(position);
                intent.putExtra(Utility.CONTACT_DATA_INTENT_DATA_NAME, userContact);
                mContactNote = userContact.Note;
                startActivityForResult(intent, Utility.CONTACT_VIEW_ACTIVITY_REQUEST_CODE);

            }
        });

        mTextViewDontHaveConnection = (TextView) v.findViewById(R.id.textViewDontHaveConnection);


        registerForContextMenu(mListViewContacts);


        mEditTextSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (mEditTextSearch.getText().length() > 0) {
                    mImageViewSearch.setVisibility(View.GONE);
                    LinkedList<User> contacts = new AgileContactsProvider(getActivity()).SelectByString(mEditTextSearch.getText().toString().trim());
                    if (contacts.size() > 0)
                        LoadContacts(contacts);
                    else
                        mListViewContacts.setAdapter(null);

                } else {
                    mImageViewSearch.setVisibility(View.VISIBLE);
                    onActivityCreated(savedInstanceState);
                }
            }
        });

        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (IsAvailableInternet()) {
            SendRequestToLoadContacts();
        } else {
            if (savedInstanceState != null && savedInstanceState.containsKey("ContactAdapter"))
                LoadContacts((LinkedList<User>) savedInstanceState.getSerializable("ContactAdapter"));
            else
                ReadContacts();
        }
    }

    private void ReadContacts() {
        AgileContactsProvider mContactProvider = new AgileContactsProvider(getActivity());
        LinkedList<User> contactList = mContactProvider.SelectContacts();
        LoadContacts(contactList);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        if (v.getId() == R.id.listViewContact) {
            menu.add("Delete");
        }
    }


    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
                .getMenuInfo();
        if (info != null) {
            if (IsAvailableInternet()) {
                String userCode = ((User) mContactAdapter.getItem(info.position)).Code;
                setUrl(Utility.DELETE_CONTACT_URL + "?userToken="
                        + Utility.getUserSession(getActivity()).UserToken + "&code=" + userCode);
                setRequestMethodType(Utility.RequestMethodType.GET);
                SendRequest(true);
                //Utility.AgileSyncUpdater(new AgileContactsProvider(getActivity()), null);
            } else
                ((MainActivity) getActivity()).mTextViewInternetConnection.setVisibility(View.VISIBLE);
        }

        return true;
    }

    public void SendRequestToLoadContacts() {
        if (IsAvailableInternet()) {
            setUrl(Utility.CONTACTS_URL + "?userToken="
                    + Utility.getUserSession(getActivity()).UserToken
                    + "&offset=0&limit=100");
            setRequestMethodType(Utility.RequestMethodType.GET);
            SendRequest(false);
            //   Utility.AgileSyncUpdater(new AgileContactsProvider(getActivity()), null);
        } else {
            ReadContacts();
        }
    }


    @Override
    protected void getResponce(String jsonResult) {

        if (!Utility.isNullOrEmpty(jsonResult)) {
            try {
                JSONObject jObject = new JSONObject(jsonResult);
                if (jObject.has("Result"))
                    jsonResult = jObject.getString("Result");
                if (!Utility.isNullOrEmpty(jsonResult) && !jsonResult.equals("null") && jsonResult.contains("[") && !jsonResult.equals("Deleted")) {
                    JSONArray jsonArray = new JSONArray(jsonResult);
                    LinkedList<User> mContactList = new LinkedList<User>();
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray
                                .getJSONObject(i);

                        mContactList.add(Utility
                                .Deserialize(User.class, jsonObject.toString()));
                    }

                    new AgileContactsProvider(getActivity()).UpdateContact(mContactList);

                    ReadContacts();

                    //LoadContacts(mContactList);
                }
                if (jsonResult.equals("Deleted"))
                    SendRequestToLoadContacts();
            } catch (Exception ex) {
                Utility.Log("ContactFragment -> getResponce ", ex);
            }
        }
    }

    private void LoadContacts(LinkedList<User> contacts) {
        if (contacts.size() > 0) {
            mTextViewDontHaveConnection.setVisibility(View.GONE);
            mListViewContacts.setVisibility(View.VISIBLE);
            Collections.sort(contacts, new Comparator<User>() {
                @Override
                public int compare(User user, User user2) {
                    return Collator.getInstance().compare(user.FirstName, user2.FirstName);
                }
            });

            mContactAdapter = new ContactAdapter(getActivity(),
                    contacts);

            mListViewContacts.setAdapter(mContactAdapter);
            mContactAdapter.notifyDataSetChanged();
        } else {
            mTextViewDontHaveConnection.setVisibility(View.VISIBLE);
            mListViewContacts.setVisibility(View.GONE);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        {
            if (requestCode == Utility.CONTACT_VIEW_ACTIVITY_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
                if (data.hasExtra(Utility.CONTACT_DATA_INTENT_DATA_NAME)) {
                    User user = (User) data.getSerializableExtra(Utility.CONTACT_DATA_INTENT_DATA_NAME);
                    if (user != null) {
                        UpdateNote(user);
                    }
                }
            }
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        if (outState != null) {
            outState.putString("NoteData", mContactNote);

            if (mContactAdapter != null && mContactAdapter.getContacts().size() > 0)
                outState.putSerializable("ContactAdapter", mContactAdapter.getContacts());
        }
    }

    @Override
    public void onViewStateRestored(Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
        if (savedInstanceState != null)
            mContactNote = savedInstanceState.getString("NoteData");
    }

    private void UpdateNote(final User user) {
        new AsyncTask<Void, Void, String>() {

            @Override
            protected String doInBackground(Void... voids) {
                try {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.accumulate("UserToken", Utility.getUserSession(getActivity()).UserToken);
                    jsonObject.accumulate("Code", Integer.valueOf(user.Code));
                    jsonObject.accumulate("NoteText", user.Note);

                    mHttpEntity = new StringEntity(jsonObject.toString(), "utf-8");
                    mHttpEntity.setContentType("application/json;charset=UTF-8");
                    mHttpEntity.setContentEncoding(new BasicHeader(
                            HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));

                    return Utility.ConnectServer(Utility.ADD_NOTE_URL, Utility.RequestMethodType.POST, mHttpEntity);
                } catch (Exception ex) {
                    Utility.Log("ContactFragment -> UpdateNote", ex);
                    return null;
                }
            }

            @Override
            protected void onPostExecute(String s) {
                if (!Utility.isNullOrEmpty(s)) {
                    new AgileContactsProvider(getActivity()).UpdateNote(user);
                    ReadContacts();
                }
            }
        }.execute();
    }
}
